package com.peng.rpc.serializer;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.peng.rpc.enumeration.RpcError;
import com.peng.rpc.enumeration.SerializerCode;
import com.peng.rpc.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022/3/3 18:58
 */
@Slf4j
public class HessianSerializer implements CommonSerializer{
    @Override
    public byte[] serialize(Object object) {
        HessianOutput hessianOutput = null;
        byte[] bytes = null;
        try (
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ) {
           hessianOutput = new HessianOutput(baos);
           hessianOutput.writeObject(object);
           bytes = baos.toByteArray();
        } catch (IOException e) {
            log.error("Hessian序列化失败");
            throw new RpcException(RpcError.SERIALIZE_FAILED);
        } finally {
            if (hessianOutput != null) {
                try {
                    hessianOutput.close();
                } catch (IOException e) {
                    log.error("关闭hessian失败：{}", e.getMessage());
                }
            }
        }
        return bytes;
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        Object res = null;
        HessianInput hessianInput = null;
        try (
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ) {
            hessianInput = new HessianInput(bais);
            res = hessianInput.readObject(clazz);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (hessianInput != null) {
                hessianInput.close();
            }
        }
        return res;
    }

    @Override
    public int getCode() {
        return SerializerCode.HESSIAN.getCode();
    }
}
